package Leo.fileIO.impl;

import Leo.fileIO.FileDownload;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Service("fileDownload")
public class FileDownloadImpl implements FileDownload {


    /**
     * 下载文件
     *
     * @param path
     */
    public void downFile(String path,HttpServletResponse response) throws IOException {
        int indexOf = path.lastIndexOf("/");
//        String fileName = path.substring(indexOf+1);
        String fileName = "hello.jpg";
//        response.setContentType("application/x-download");
        //添加报文头,只有在报文里添加了"Content-disposition", "attachment; filename="打开文件的时候就会以下载文件的形式弹出，
        //如果不加这个报文头的话，就是将"/images/111.jpg"这个文件写入到浏览器，就是直接在浏览器中呈现出图片了
        //attachment; filename="+ fileName其实就是下载的时候将111.jpg这个文件取个“hello”的别名
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
        ServletOutputStream outputStream = response.getOutputStream();
        fileToOutputStream(path,outputStream);
//        outputStream.flush();
    }

    /**
     * 让文件以指定形式显示
     *
     * @param path
     */
    public void transFile(String path,HttpServletResponse response) throws IOException {
        response.setContentType("image/jpeg");
        ServletOutputStream outputStream = response.getOutputStream();
        fileToOutputStream(path,outputStream);
//        outputStream.flush();
    }

    /**
     * 此处代码，参考commons.io.IoUtils.copy
     * @param inputStream
     * @param outputStream
     * @return
     */
    private OutputStream ioCopy(InputStream inputStream,OutputStream outputStream) throws IOException {
        byte[] buff = new byte[1000];
        int n ;
        while(-1 != (n = inputStream.read(buff))){
            outputStream.write(buff,0,n);
        }
        return outputStream;
    }

    /**
     * 文件转为输出流
     * @param path
     * @param outputStream
     * @return
     */
    public OutputStream fileToOutputStream(String path,OutputStream outputStream) throws IOException {
        File file = new File(path);
        FileInputStream inputStream = new FileInputStream(file);
        ioCopy(inputStream,outputStream);
        return outputStream;
    }
}
